import Addition from "@/components/Addition";
import Addition2 from "@/components/Addition2";
import { s_getcommontableinfo, s_getSysInfo, s_operateInfo, s_saveSysInfo } from "@/services/basis";
import { ProCard, ProForm, ProFormDatePicker, ProFormInstance, ProFormItemProps, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-components";
import { useRequest } from "@umijs/max";
import { Button, Card, Col, Divider, Flex, Form, Input, message, Radio, Row, Space, Tabs, TabsProps } from "antd";
import { json } from "express";
import moment from "moment";
import { useRef, useState } from "react";
import { getSelection } from "@/services/selections";

const App:React.FC=()=>{
  const [addition,setAddition]=useState([]);
  const [canInfo,setCanInfo]=useState(true);
  const [activeKey,setActiveKey]=useState('do');
  const [registInfo,setRegistInfo]=useState<any>({});
  const [typeOption,setTypeOption]=useState([]);

  const [sysInfo,setSysInfo]=useState<DataType>();

//   useRequest(()=>s_getSysInfo({x_id:1}),{
//      onSuccess:(data)=>{
//          setSysInfo(data);
//          form_ref.current?.setFieldsValue({
//              x_id:data?.x_id,creditcode:data?.creditcode,name:data?.name,code:data?.code,
//              address:data?.address,telephone:data?.telephone,mobilephone:data?.mobilephone,
//              contactor:data?.contactor,email:data?.email,present:data?.present,
//              operater_id:data?.operater_id,status:data?.status==null?1:data?.status,
//              operater_time:moment(moment(data?.operate_time).toDate()).format('YYYY-MM-DD')
//          });
//      }
//  });

 const form_ref=useRef<ProFormInstance>();
 const form_ref_do=useRef<ProFormInstance>();

 //由于是按下拉框多选项赋值，因此需要先生成选项，才能取数后匹配进label。否则显示为[null,null...] 2025-02-12
 useRequest(async ()=>await getSelection({source: 'base_industry' }),
             {
              onSuccess:(data)=>{
                       var x2=data.map((item:any)=>({value:item.id,label:item.name,key:item.id,title:item.name}));
                      //  alert(JSON.stringify(data));
                       setTypeOption(x2);
                }
      });
 
 interface DataType{
        x_id:number,
        creditcode:string,
        code:string,
        name:string,
        address:string,
        email:string,
        telephone:string,
        mobilephone:string,
        contactor:string,
        present:string,
        operate_time:string,
        operater_id:string,
        status:number,
    }

    function doRegist(){
        const fdata=form_ref_do.current?.getFieldsValue();
        const x=form_ref_do.current?.getFieldValue('x_id');
        if(x!=undefined){
            // alert(fdata.invite_xid_name);
            setCanInfo(false);
            setActiveKey('info'); 
            form_ref.current?.setFieldsValue({...registInfo});
        }else
          alert('不存在的注册邀请');
        
        

    };

    const tab_regist=<>
       <ProForm submitter={false} formRef={form_ref_do} onFinish={()=>doRegist()}
          layout="horizontal" labelCol={{span:5,offset:0}} labelAlign="left"
       >
           <Row gutter={8}>
              <Col span={8}>
              </Col>
              <Col span={8}>
                  <ProFormText name='invite_code' label='邀请码/6位'   width={300} 
                    rules={[{required:true,message:'必须输入'}]}
                    fieldProps={{
                        maxLength:6,
                        async onChange(e){
                             const value=e.target.value;
                             var x:any={};
                             if(value.toString().length==6){
                                // alert(value);
                                x=await s_getcommontableinfo({source:'get_sys_regist',fdata:{invite_code:value}});
                                // alert(JSON.stringify(x.data[0][0]));
                                if(x.success&&x.data[0].length!=0){
                                    //   alert(JSON.stringify(x.data[0][0].invite_enddate));
                                    form_ref_do.current?.setFieldsValue({
                                       invite_xid:x.data[0][0].invite_xid,
                                       invite_xid_name:x.data[0][0].invite_xid_name,
                                       x_id:x.data[0][0].x_id,
                                       invite_time:x.data[0][0].invite_time,
                                       invite_enddate:x.data[0][0].invite_enddate,
                                    });
                                     
                                    setRegistInfo(x.data[0][0]);
                                    // form_ref.current?.setFieldsValue({
                                    //     x_type:x.data[0][0].x_type,
                                    //     state:x.data[0][0].state==undefined?10:x.data[0][0].state,
                                    // });
                                }
                                else{
                                   message.warning('没有此注册码，请核实后重新输入');
                                   form_ref_do.current?.resetFields();
                                }
                            }}
                         }}
                  />
                  <ProFormText name='mobilephone' label='注册手机号'  width={300} 
                     rules={[{required:true,message:'必须输入'}]}
                  />
                  
                  <ProFormText name='invite_xid_name' label='邀请单位' width={300} />
                  <ProFormDatePicker name='invite_time' label='邀请日期' width={300} />
                  <ProFormDatePicker name='invite_enddate' label='截止日期' width={300}/>
                  <ProFormText name='invite_xid' label='邀请ID' hidden={true} />
                  <ProFormText name='x_id' label='XID' hidden={true} />
              </Col>
          </Row>
       </ProForm>
       <br/>
       <Button onClick={()=>form_ref_do.current?.submit()} style={{marginLeft:500,width:200}}>开始注册</Button>
    </>;

    const tab_info=<><ProForm formRef={form_ref} style={{width:800,marginLeft:100}} 
      submitter={false} 
      onFinish={()=>saveSysInfo()} 
      labelCol={{span:6,offset:0}} labelAlign="left" layout="horizontal" labelWrap
      initialValues={registInfo==undefined?{
                      state:10,
                      x_type:1,
                     }:{
                      ...registInfo,
                      salecategory:registInfo.salecategory==undefined?null:JSON.parse(registInfo.salecategory),
                      purchasecategory:registInfo.purchasecategory==undefined?null:JSON.parse(registInfo.purchasecategory),
                      // purchasecategory:[7,8],
                     }}
      >
     <Row gutter={20}>
         <Col span={10}>
              <ProFormText label='ID'  name='x_id' disabled />
              <ProFormText label='统一社会信息代码'  name='creditcode'
                  rules={[{required:true,message:'统一社会信息代码必须输入。'}]}/>
              <ProFormText label='单位编码'  name='code'
                 rules={[{required:true,message:'单位名称必须输入。'}]}/>
              <ProFormText label='单位名称'  name='name'
                 rules={[{required:true,message:'单位名称必须输入。'}]}/>
             <ProFormText label='注册手机号'  name='mobilephone' 
                   rules={[{required:true,message:'手机号必须输入。'}]} />
              
         </Col>
         <Col span={4}></Col>
         <Col span={10}>
              <ProFormText label='单位邮箱'  name='email'/>
              <ProFormText label='法人代表' name='present'/>
              <ProFormText label='联系人'  name='contactor'/>
              <ProFormText label='联系电话'  name='telephone'/>
              <ProFormText label='地址'  name='address' />

              
              <ProFormText name='operater_id' hidden />
              <ProFormText name='operate_time' hidden/>
         </Col>
     </Row>
     <Divider>为了更方便潜在客户或供应商快捷找到您，请填写下述信息哦！</Divider>
     
     <Row gutter={20}>
      <Col span={10}>
        <ProFormSelect name='purchasecategory' label='采购类目'
           fieldProps={{
            mode:'multiple',
            labelInValue:true,
            allowClear:true,
            
            // defaultValue:registInfo.purchasecategory,
           }}
          //  request={async ()=>{
          //                    var x:any=await getSelection({source: 'base_industry' });
          //                    var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
          //                    return x2;
          //                    }}
          options={typeOption}
          
        />
       
      </Col>
      <Col span={4}>
      </Col>
      <Col span={10}>
          <ProFormSelect name='salecategory' label='供货类目'
fieldProps={{
  mode:'multiple',
  labelInValue:true,
  allowClear:true,
  // defaultValue:registInfo.salecategory
 }}
      // request={async ()=>{
      //              var x:any=await getSelection({source: 'base_industry' });
      //              var x2=x.data.map((item:any)=>({value:item.id,label:item.name}));
      //              return x2;
      //              }}
      options={typeOption}
          />
          
      </Col>
     </Row>
     <Row>
         <Col span={24}>
              <ProFormRadio.Group name='x_type' label='伙伴类型'
                 options={[{value:1,label:'供应商'},{value:2,label:'客户'},{value:3,label:'全方位伙伴'}]}
              />
              <ProFormRadio.Group label='账号状态'  name='state'
                     options={[{label:'未提交',value:10},{label:'已提交',value:11},
                     {label:'撤销提交',value:12},{label:'已准入',value:5,style:{color:'red'}},
                     {value:6,label:'拒绝准入'},{value:7,label:'撤销准入'}]}
                 />
         </Col>
     </Row>
     <Space>
        <Button onClick={()=>saveSysInfo()}  >保存注册信息</Button>
        <Button onClick={()=>operateInfo(21)}>提交申请</Button>
        <Button  onClick={()=>operateInfo(22)}>撤回申请</Button>
     </Space>
    </ProForm></>;

    const tab_addition=<>
           {/* {JSON.stringify(addition)}
           {JSON.stringify(registInfo)} */}

            <Addition2  source_xid={registInfo==undefined&&registInfo.x_id==undefined?0:registInfo.x_id} 
                        setData={setAddition} 
                        type={2} 
                        fdata={{source_table:'addition_sys_regist',
                               source_value:registInfo==undefined||registInfo.addition==undefined?'':registInfo.addition,
                               source_id:registInfo==undefined||registInfo.x_id==undefined?0:registInfo.x_id,
                               source_field:'addition',
                               source_code:registInfo==undefined||registInfo.creditcode==undefined?'':registInfo.creditcode,
                        // fdata={{source_table:'addition_sys_regist',
                        //     source_value:registInfo==undefined||registInfo.addition==undefined?'':registInfo.addition,
                        //     source_id:0,
                        //     source_field:'addition',
                        //     source_code:'',
                       }}  />
                       
            </>;
    
    const tabItems:TabsProps['items']=[
      {
        label:'准备注册',
        key:'do',
        children:tab_regist,
      },
      {
        label: '注册信息',
        children: tab_info,
        key: "info",
         disabled:canInfo,
      },
      {
        key:'addition',
        label:'附件',
        children:tab_addition,
        disabled:canInfo,
      }
    ];

    async function saveSysInfo(){
        const fdata=form_ref.current?.getFieldsValue();
        
        var salecategory:any[]=[];
        var salecategory2:any[]=[];
        var purchasecategory:any[]=[];
        var purchasecategory2:any[]=[];

        if(fdata.salecategory!=undefined&&fdata.salecategory!=null)
        fdata.salecategory.map((item:any)=>{
          salecategory.push(item.value);
          salecategory2.push(item.label);
        });

        if(fdata.purchasecategory!=undefined&&fdata.purchasecategory!=null)
        fdata.purchasecategory.map((item:any)=>{
          purchasecategory.push(item.value);
          purchasecategory2.push(item.label);
        });

        const fdata2={...fdata,
          operate_time:moment(moment(fdata.operate_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
          salecategory:salecategory.length==0?null:salecategory,
          salecategory2:salecategory2.length==0?null:salecategory2,
          purchasecategory:purchasecategory.length==0?null:purchasecategory,
          purchasecategory2:purchasecategory2.length==0?null:purchasecategory2,
  
         };
        alert(JSON.stringify(fdata2));
        //执行保存
        const x=await s_saveSysInfo({fdata:fdata2});
        if(x.success)
            message.success('系统信息保存成功！');
        else
            message.error('系统信息保存错误，请检查！');
     }
     
     function switchTab(key:string){
        setActiveKey(key);
        //   alert(key);
        if(key=='do'){
          setRegistInfo({});
          form_ref_do.current?.resetFields();
          setCanInfo(true);
        }
     }
    //提交或撤销
       async function operateInfo(n:number){
         // source,x_id,operater_id,otype,id
          const fdata=form_ref.current?.getFieldsValue();
          if(fdata.x_id!=undefined&&fdata.creditcode!=undefined&&fdata.creditcode!=''){
          const x=await s_operateInfo({x_id:1,source:'sys_regist',operater_id:1,otype:n,id:fdata.x_id});
          if(x.success){
            message.success(n==11?'提交申请成功':'撤回申请成功');
            form_ref.current?.setFieldValue('state',n-10);
          }else
            message.error('操作错误，请联系管理员。');
        }else
          message.warning('请先保存注册信息后，再提交。')
      }

    //  主界面================================================================================================
    return(
     <ProCard title='我要注册' style={{height:700}} 
       >
        {/* {JSON.stringify(sysInfo)} */}
        <Tabs items={tabItems} activeKey={activeKey} onTabClick={(key)=>switchTab(key)}/>
        
     </ProCard>
);
}

export default App;